import "./index.css";

import clsx from "classnames";
import { GridBoxProps } from "./type";
import { useComponent } from "../factory";

const GridBox = <T extends Record<string, any>>(props: GridBoxProps<T>) => {
  const { size, items, itemCls, allowClear = true, itemActiveCls = "" } = props;

  const {
    className,
    style,
    val: activeKey,
    action,
  } = useComponent({
    ...props,
    wrapperCls: "grid-box-container",
    wrapperStyle: {
      width: size,
      height: size,
    },
  });

  return (
    <div style={style} className={className}>
      {items.map((item) => {
        const { key, render } = item;

        return (
          <div
            key={key as string}
            className={clsx(
              "grid-box-item",
              {
                active: activeKey === key,
                [itemActiveCls]: activeKey === key,
              },
              itemCls
            )}
            style={{
              width: `${100 / Math.sqrt(items.length)}%`,
            }}
            onClick={() => {
              const isEqual = activeKey === key;

              if (isEqual) {
                if (allowClear) {
                  action(null);
                }
              } else {
                action(key);
              }
            }}
          >
            {typeof render === "function" ? render() : render}
          </div>
        );
      })}
    </div>
  );
};

export default GridBox;
